<template>
	<div v-loading="loading">
		<AplidForm v-model="formModel" v-if="!loading" v-bind="formConfig" @submit="onSubmit"></AplidForm>
    <PageLoading v-if="loading" />
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { ElMessage } from 'element-plus'

const props = defineProps<{
	nowRowData: any
  tempConfig?: any
}>()
const emit = defineEmits(['refresh'])

const formModel: any = ref({})

const formConfig = ref({
	inline: false,
	showBtn: true,
	labelPosition: 'top',
	labelWidth: '120px',
	column: [],
})

const loading = ref(false)

const onSubmit = (form, done) => {
	let baseApi = formModel.value.id ? 'view_tableItem_edit' : 'view_tableItem_add'
	const query = {
		id: undefined,
		tableTemplateId: props.nowRowData.tableTemplateId,
		itemData: JSON.stringify(form),
		fieldId: props.nowRowData.id,
		fieldName: props.nowRowData.templateName,
		result: props.nowRowData.result || props.nowRowData.uniqueKey,
	}
	if (form.id) {
		query.id = form.id
	}
	apiMod[baseApi](query)
		.then(() => {
			emit('refresh')
			ElMessage.success('操作成功')
			done(form)
		})
		.catch(() => {
			done()
		})
}
const getInitData = () => {
	loading.value = true
	if (props.nowRowData.id) {
		formModel.value = props.nowRowData.itemData
		formModel.value.id = props.nowRowData.id
	}
	if (props.tempConfig.column) {
		formConfig.value.column = props.tempConfig.column
		formConfig.value.labelPosition = props.tempConfig.labelPosition
    setTimeout(() => {
      loading.value = false
    },100);
		return
	}

	apiMod
		.view_tableTemplate_id(props.nowRowData.tableTemplateId)
		.then((res) => {
			loading.value = false
			const config = res.data?.jsonStr || {}
			formConfig.value.column = [...config.column]
			formConfig.value.labelPosition = config.labelPosition
		})
		.catch(() => {
			loading.value = false
		})
}

onMounted(() => {
	getInitData()
})
</script>

<style scoped></style>
